#include "tdomain.h"

#include "precomp.h"
//#include <QApplication>
//#include <QScreen>
//#include <QDateTime>
//#include <QFile>
//#include <QMutex>
//#include <QDir>


void outPutMsg(QtMsgType msgType, const QMessageLogContext &context, const QString &strText)
{
    static QMutex mutex;
    mutex.lock();

    QString strMsg("");
    // 设置输出信息格式


    switch (msgType) {
    case QtDebugMsg: {
        strMsg = QString("Debug");
        break;
    }
    case QtInfoMsg: {
        strMsg = QString("Info");
        break;
    }
    case QtWarningMsg: {
        strMsg = QString("Warning");
        break;
    }
    case QtCriticalMsg: {
        strMsg = QString("Critical");
        break;
    }
    case QtFatalMsg: {
        strMsg = QString("Fatal");
        break;
    }
    }

    QString strDateTime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz");
    QString fileName =context.file;
    QStringList listStr = fileName.split("/"); // 以空格为分隔符进行分割
    fileName=listStr.at(listStr.size()-1);
    QString strMessage = QString("[%1][%2][%3]-%4:%5\r\n").arg(strDateTime).arg(fileName).arg(context.line).arg(strMsg).arg(strText);

    QString strPlaceDir = QCoreApplication::applicationDirPath()+"/log";//当前程序运行路径
    QDir directory(strPlaceDir);//如果路径不存在，则创建
    if (!directory.exists())
        directory.mkpath(strPlaceDir);
    QString logFileName =strPlaceDir+"/"+QString(QDate::currentDate().toString("yyyy-MM-dd") + ".txt");
    QFile file(logFileName);
    file.open(QIODevice::WriteOnly | QIODevice::Append);
    QTextStream text_stream(&file);
    text_stream<<strMessage;
    file.close();

    fprintf(stderr, strMessage.toLocal8Bit().data());
    fflush(stderr);
    // 解锁
    mutex.unlock();
}


int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    qInstallMessageHandler(outPutMsg);
    qDebug("This is a debug message.");
    qWarning("This is a warning message.");
    qCritical("This is a critical message.");
    qInfo("This is a info message.");

    TDomain w;
    w.setStyleSheet("QMainWindow::titleBar  { background-color: red; }");
    w.resize(QGuiApplication::primaryScreen()->availableSize()*2/3);
    QScreen * scr = a.primaryScreen();
    int scr_w = scr->size().width();
    int scr_h = scr->size().height();
    w.move ((scr_w - w.width())/2,(scr_h - w.height())/2);
    w.show();



    return a.exec();
}
